package com.boc.langxiang.presenter.common;


import com.boc.langxiang.contract.common.RegistContract;
import com.boc.langxiang.entity.request.RegistRequest;
import com.boc.langxiang.entity.request.SmsCodeRequest;
import com.boc.langxiang.entity.response.BaseResponse;
import com.boc.langxiang.entity.response.SmsCodeEntity;
import com.boc.langxiang.entity.response.UserInfo;
import com.boc.langxiang.manager.UserInfoManager;
import com.boc.langxiang.net.ApiService;
import com.boc.langxiang.net.HandleErrorSubscriber;
import com.boc.langxiang.net.NetClient;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * CreateTime: 2016-06-14上午10:40
 * Author: wjkjinke00@126.com
 * Description:
 */
public class RegistPresenter implements RegistContract.Presenter {

    private RegistContract.View mView;
    private ApiService mService;

    public RegistPresenter(RegistContract.View view) {
        mService = NetClient.getInstance().net().create(ApiService.class);
        mView = view;
    }

    @Override
    public void sendCode(String phone) {
        SmsCodeRequest request = new SmsCodeRequest();
        request.phone = phone;
        Observable<BaseResponse<SmsCodeEntity>> register = mService.smsCode(request.params());
        register.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new HandleErrorSubscriber<BaseResponse<SmsCodeEntity>>(mView) {
                    @Override
                    public void onSuccess(BaseResponse<SmsCodeEntity> response) {
                        SmsCodeEntity smsCodeEntity = response.getContent();
                        mView.onGetSmsCodeSuccess(smsCodeEntity);
                    }
                });
    }

    @Override
    public void regist(RegistRequest request) {
        mView.showLoading();
        Observable<BaseResponse<UserInfo>> register = mService.regist(request.params());
        register.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new HandleErrorSubscriber<BaseResponse<UserInfo>>(mView) {
                    @Override
                    public void onSuccess(BaseResponse<UserInfo> response) {
                        UserInfo userInfo = response.getContent();
                        UserInfoManager.getInstance().setUserInfo(userInfo);
                        mView.registeSuccess();
                    }
                });
    }
}
